package org.dandelion.core.message
{
	import flash.utils.Dictionary;
	
	import mx.messaging.Channel;
	import mx.messaging.ChannelSet;
	import mx.messaging.Consumer;
	import mx.messaging.Producer;
	import mx.messaging.channels.AMFChannel;
	import mx.messaging.config.ServerConfig;
	import mx.messaging.events.MessageEvent;
	
	import org.dandelion.config.DandelionCofig;
	import org.dandelion.core.channel.ChannelSetFactory;
	import org.dandelion.erro.DandelionError;
	import org.dandelion.erro.DandelionErrorInfo;
	
	public class MessageService implements IMessageService
	{
		
		private static var _instance:MessageService = null;//唯一实例
		
		protected var _channel:String;
		
		private var _channelSet:ChannelSet;
		
//		private var _consumers:Dictionary = new Dictionary();//Consumer的Map集合，存放各种Consumer
		
//		private var _producers:Dictionary = new Dictionary();//Producer的Map集合，存放各种Producer
		
		
		public function MessageService()
		{
//			_url = GetServerUrl.url+"/";
//			_myPollingAMF = new AMFChannel(_url+"my-polling-amf", _url+"messagebroker/amfpolling");
//			_myPollingAMF.pollingEnabled = _pollingEnabled;//轮询
//            _myPollingAMF.pollingInterval = _pollingInterval;//隔多长时间询问一次 1miao
//            _channelSet = new ChannelSet();
//            _channelSet.addChannel(_myPollingAMF);
			_channel = DandelionCofig.defaultMessageChannel;
			_channelSet = ChannelSetFactory.getInstance().getChannelSet(_channel);
			if(_instance) throw new Error("Error: Singletons can only be instantiated via instance() method!");
			MessageService._instance = this;
		}
		
		
		
		public static function instance():MessageService{
			if(!_instance){
				_instance = new MessageService();
			}
			return _instance;
		}
		
		/**
		 * 创建一个消息订阅
		 * @param destination String 目标
		 * @param subtopic String 订阅的主题
		 * @param messageHandler Function
		 * return Consumer
		 **/
		public function createConsumer(destination:String,subtopic:String,messageHandler:Function):Consumer{
			var c:Consumer = new Consumer();
			c.destination = destination;
			c.subtopic = subtopic;
			c.addEventListener(MessageEvent.MESSAGE, messageHandler);     
			c.channelSet = _channelSet;
			c.subscribe();
			return c;
		}
		
	}
}